package com.guohao.reggie.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guohao.reggie.common.R;
import com.guohao.reggie.entity.Category;
import com.guohao.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
//
///**
// * 文件上传
// * 文件下载
// * MultipartFile file 参数名 必须是 和name保持一致 file
// */
//@Slf4j
//@RestController
//@RequestMapping("/common")
//public class CommonController {
//    @Value("${reggie.path}")
//    private String basePath;
//
//    @PostMapping("/upload")
//    public R<String> upload(MultipartFile file) throws IOException {
//        //临时文件  需要转存到指定为止, 否则本次 请求结束 回删除
//     log.info("file :{}" ,file.toString());
//
////     // 上传图片 原始文件名
////        String originalFilename = file.getOriginalFilename();
////        // 截取 后缀  .jpg
////        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
////
////        // 使用 UUID 重新生产文件名 防止文件名重复 导致覆盖
////        String fileName = UUID.randomUUID().toString() + substring;
////        // Endpoint以杭州为例，其它Region请按实际情况填写。
////        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
////// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
////        String accessKeyId = "LTAI5tCpWv7yK3B36FrDLbKM";
////        String accessKeySecret = "tjzgkOQ4M8WNV9ioxhG5PgALzYrhYD";
////
////// 创建OSSClient实例。
////        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
////
////// 上传文件流。
////
////        ossClient.putObject("gedeer", fileName, file.getInputStream());
////
////// 关闭OSSClient。
////        ossClient.shutdown();
//
//
//    //创建一个目录对象
//        File dir = new File(basePath);
//        //判断当前目录是否存在  不存在就创建
//        if (!dir.exists()){
//            //创建
//            dir.mkdirs();
//        }
//
//        try {
//            // 将临时文件 转存到指定位置
//            file.transferTo(new File(basePath + fileName));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return R.success(fileName);
//    }
//
//    /**
//     * 文件下载
//     * @param name
//     * @param response
//     */
//    @GetMapping("/download")
//    public void download(String name, HttpServletResponse response) {
//
//
//    }
//
//
//
//
////            if (content != null) {
////                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
////                while (true) {
////                    String line = reader.readLine();
////                    if (line == null) break;
////                    System.out.println("\n" + line);
////                }
////                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
////                content.close();
////            }
////        } catch (OSSException oe) {
////            System.out.println("Caught an OSSException, which means your request made it to OSS, "
////                    + "but was rejected with an error response for some reason.");
////            System.out.println("Error Message:" + oe.getErrorMessage());
////            System.out.println("Error Code:" + oe.getErrorCode());
////            System.out.println("Request ID:" + oe.getRequestId());
////            System.out.println("Host ID:" + oe.getHostId());
////        } catch (ClientException ce) {
////            System.out.println("Caught an ClientException, which means the client encountered "
////                    + "a serious internal problem while trying to communicate with OSS, "
////                    + "such as not being able to access the network.");
////            System.out.println("Error Message:" + ce.getMessage());
////        } catch (IOException e) {
////            e.printStackTrace();
////        } finally {
////            if (ossClient != null) {
////                ossClient.shutdown();
////            }
////        }
////    }
//
//    }
////        try {
////            // 输入流, 读取文件内容
////            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
////
////            // 输出流, 协会浏览器 浏览器展示图片
////            ServletOutputStream outputStream = response.getOutputStream();
////
////            int len;
////            byte[] bytes = new byte[1024];
////
////            while ((len=fileInputStream.read(bytes)) != -1){
////                outputStream.write(bytes,0,len);
////                //刷新流
////                outputStream.flush();
////            }
////            // 关流
////            fileInputStream.close();
////            outputStream.close();
////
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
////
////    }
//
////}
/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
